package net.wenku8.reader.view.online

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONObject
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.api.BookApi
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.enums.KeyOnlineOpenHis
import net.wenku8.reader.enums.KeyOnlineReadHis
import net.wenku8.reader.model.book.BookPreviewInfo
import net.wenku8.reader.model.book.Chapter
import net.wenku8.reader.model.book.Volume
import net.wenku8.reader.state.StateReadOnline
import net.wenku8.reader.view.common.BaseViewModel
import java.util.Date

class OnlineDetailViewModel : BaseViewModel() {
    var bookPreviewInfo by mutableStateOf(BookPreviewInfo())
    var bookDesc by mutableStateOf("")
    val volumeList = mutableStateListOf<Volume>()
    var inBookcase by mutableStateOf(false)
    var hisChapter by mutableStateOf(Chapter())
    var hisLoad by mutableStateOf(false)

    fun initData() {
        dataLoading.value = true
        viewModelScope.launch(Dispatchers.IO) {
            loadBookInfo()
            loadBookDesc()
            loadBookVolume()
            inBookcase = StateReadOnline.bookCaseList.value.contains(StateReadOnline.bookId.value)
            StateReadOnline.bookCaseRefresh.value = true
            dataLoading.value = false
            loadReadHis()
            saveOpenHis()
        }
    }

    private fun loadBookInfo(){
        val bookInfoResp = BookApi.getBookInfo(StateReadOnline.bookId.value)
        if (ApiResult.isSuccess(bookInfoResp)){
            val book = bookInfoResp.data!!
            Log.i("initData:", JSON.toJSONString(book))
            val previewInfo = BookPreviewInfo()
            previewInfo.bookId = book.bookId
            previewInfo.title = book.title
            previewInfo.author = book.author
            previewInfo.bookStatus = book.bookStatus
            previewInfo.lastUpdate = book.lastUpdate
            bookPreviewInfo = previewInfo
        }
    }
    private fun loadBookDesc(){
        val bookDescResp = BookApi.getBookDesc(StateReadOnline.bookId.value)
        if (ApiResult.isSuccess(bookDescResp)){
            bookDesc = bookDescResp.data?:"无"
        }
    }

    private fun loadBookVolume(){
        val bookVolumeResp = BookApi.getBookVolume(StateReadOnline.bookId.value)
        if (ApiResult.isSuccess(bookVolumeResp)){
            val vList = bookVolumeResp.data!!
            volumeList.clear()
            volumeList.addAll(vList)
        }
    }

    private fun loadReadHis(){
        val hisData = MMKV.defaultMMKV().decodeString(KeyOnlineReadHis + StateReadOnline.bookId, null)
        if(hisData != null){
            hisChapter = JSON.parseObject(hisData, Chapter::class.java)
            hisLoad = true
        }
    }

    private fun saveOpenHis(){
        val hisData = MMKV.defaultMMKV().decodeString(KeyOnlineOpenHis, null)
        var json = JSONObject()
        if(hisData != null){
            json = JSON.parseObject(hisData)
        }
        json.put(StateReadOnline.bookId.value, Date().time)
        MMKV.defaultMMKV().encode(KeyOnlineOpenHis, json.toJSONString())
    }


    fun addBookcase(){
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = BookApi.addBookCase(StateReadOnline.bookId.value)
            if (ApiResult.isSuccess(apiResult)){
                inBookcase = true
                showSnackbar("添加成功")
            }else{
                showSnackbar(apiResult.message)
            }
        }
    }

    fun delBookcase(){
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = BookApi.delBookCase(StateReadOnline.bookId.value)
            if (ApiResult.isSuccess(apiResult)){
                inBookcase = false
                showSnackbar("删除成功")
            }else{
                showSnackbar(apiResult.message)
            }
        }
    }

    fun bookVote(){
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = BookApi.bookVote(StateReadOnline.bookId.value)
            if (ApiResult.isSuccess(apiResult)){
                showSnackbar("推荐成功")
            }else{
                showSnackbar(apiResult.message)
            }
        }

    }

    fun toOnlineRead(chapter : Chapter){
        StateReadOnline.chapter.value = chapter
        StateReadOnline.volumeList.value = ArrayList(volumeList)
    }

}